package service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.Cart;
import dao.OrderDAO;
import entity.CartItem;
import entity.Item;
import entity.Order;
import entity.ReceiveAddress;
import entity.User;
import service.CartService;
import service.OrderService;
import util.CookieUtil;
import util.ObjectFactory;
import util.OrderCodeUtil;

public class OrderServiceImpl implements OrderService{
	public List<ReceiveAddress> getAddresses(Map<String, Object> session) throws Exception{
		User user = (User) session.get("user");
		OrderDAO dao = ObjectFactory.getInstance(OrderDAO.class);
		return dao.findByUserId(user.getId());
	}
	public ReceiveAddress getAddress(Map<String, Object> session,int addrId)throws Exception{
		OrderDAO dao = ObjectFactory.getInstance(OrderDAO.class);
		return dao.findById(addrId);
	}
	public List saveOrder(ReceiveAddress address,Map<String, Object> session,HttpServletResponse httpRes,HttpServletRequest httpReq) throws Exception{
		List result = new ArrayList();
		OrderDAO dao = ObjectFactory.getInstance(OrderDAO.class);
		Order order = new Order();
		order.setFullAddress(address.getFullAddress());
		order.setMobile(address.getMobile());
		order.setOrderTime(System.currentTimeMillis());
		order.setPhone(address.getPhone());
		order.setPostalCode(address.getPostalCode());
		order.setReceiveName(address.getReceiveName());
		CartService cart = CartFactory.getInstance(session, httpReq);
		order.setTotalPrice(cart.cost());
		double cost = cart.cost();
		result.add(cost);
		User user = (User) session.get("user");
		order.setUserId(user.getId());
		address.setUserId(user.getId());
		//设置订单号
		order.setStatus(0);
		int oid = dao.saveOrder(order);//保存订单
		result.add(oid);
		if(dao.findByFullAddress(address.getFullAddress())==null){
			dao.saveAddress(address);//保存地址
		}else {
			dao.updateAddress(address);
		}
		//保存订单明细
		for (CartItem c : cart.getProds(true)) {
			Item item = new Item();
			item.setAmount(c.getQty()*c.getPro().getDangPrice());
			item.setDangPrice(c.getPro().getDangPrice());
			item.setOrderId(oid);
			item.setProductId(c.getPro().getId());
			item.setProductName(c.getPro().getProductName());
			item.setProductNum(c.getQty());
			dao.saveItem(item);
		}
		cart.clear();
		CookieUtil.delCookie("cart", httpRes);
		return result;
	}
}
